﻿using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Linq;

namespace Aspfm.Html
{
    public class AspfmCreate
    {
        private string RowHtml = "";
        private int colcount = 100;
        List<AspfmDataSource> MyDataSql = new List<AspfmDataSource>();

        private Dictionary<string, string> JsBandHtml = new Dictionary<string, string>();
        private Dictionary<string, string> JsBandHtml_col = new Dictionary<string, string>();
        private Dictionary<string, string> JsBandHtml_Data = new Dictionary<string, string>();
        private StringBuilder sbHtmlJs = new StringBuilder();
        private StringBuilder sbHtmlScript = new StringBuilder();

        private void AddJsBand(string key,string value,bool isdata=false,bool iscol=false)
        {
            if (isdata)
            {
                if (iscol)
                {
                    QueryCols(key, value, JsBandHtml_col);
                }
                else
                {
                    QueryCols(key, value, JsBandHtml_Data);
                }
            }
            else
            {
                string[] strs1 = key.Split(',');
                foreach (string str in strs1)
                {
                    QueryCols(str, value, JsBandHtml);
                }
            }
            
        }

        private static void QueryCols(string key, string value, Dictionary<string, string> dic)
        {
            if (dic.ContainsKey(key))
            {
                if (!("," + dic[key] + ",").Contains("," + value + ","))
                {
                    dic[key] = dic[key] + "," + value;
                }
            }
            else
            {
                dic.Add(key, value);
            }
        }

        public string CreateHtml(AspfmAll AspfmAll, string NewFileName)
        {
            MyDataSql = AspfmAll.MyDataSql;
            RowHtml = AspfmAll.RowHtml.html;

            StringBuilder sbhtml = CreateHtml(AspfmAll.DesignList, AspfmAll.ALLWidth+20, AspfmAll.ALLHeight+20,"1");
           
            string html = AspfmAll.WebFromHtml.html.Replace("@Aspfm-text", Path.GetFileNameWithoutExtension(NewFileName));
            html = html.Replace("@Aspfm-正文", sbhtml.ToString());
            html = html.Replace("@Aspfm-HtmlCss", "");
            html = html.Replace("@Aspfm-HtmlScript", sbHtmlScript.ToString());
            StringBuilder newobjjs = new StringBuilder();
            StringBuilder sbjs = CreateJS(AspfmAll, ref newobjjs);
            html = html.Replace("@Aspfm-HtmlJs",newobjjs.ToString()+ sbHtmlJs.ToString());
            html = html.Replace("@Aspfm-JS", sbjs.ToString());

            if (File.Exists(NewFileName))
            {
                try
                {
                    File.Delete(NewFileName);
                }
                catch { }
            }
            File.AppendAllText(NewFileName, html, Encoding.UTF8);
            return NewFileName;
        }
        public StringBuilder CreateJS(AspfmAll AspfmAll,ref StringBuilder newObjJs)
        {
            StringBuilder sbhtml = new StringBuilder();
            if (AspfmAll != null)
            {
                if (AspfmAll.MyParams != null)
                {
                    foreach (AspfmParams bp in AspfmAll.MyParams)
                    {
                        string strhtml = GetHtml("全局参数", bp.strKey, "Aspfm.Data.Global.");
                        sbhtml.AppendLine("/*全局变量：" + bp.strKey + "*/");
                        sbhtml.AppendLine(bp.CodeMain.Replace("@参数名称", bp.strKey).Replace("@Aspfm-bandjs", strhtml));
                    }
                }
                if (AspfmAll.MyDataSql != null)
                {
                    foreach (AspfmDataSource bp in AspfmAll.MyDataSql)
                    {
                        if (bp.execList != null)
                        {
                            if (bp.execList.Count > 0)
                            {
                                newObjJs.AppendLine("/*自动定义SQL执行对象*/");
                                foreach (AspfmExecSql bds in bp.execList)
                                {
                                    newObjJs.AppendLine("Aspfm.Data." + bp.strKey + "_" + bds.strKey + "=new Object();");
                                }
                            }
                        }
                        if (bp.procList != null)
                        {
                            bool ishadProcContext = false;
                            foreach (AspfmProcSql bds in bp.procList)
                            {
                                if (bds.isQuery)
                                {
                                    sbhtml.AppendLine("/*存储过程：" + bp.strKey + "_" + bds.strKey + "*/");
                                    sbhtml.AppendLine(bds.Js.Replace("@参数名称", bp.strKey + "_" + bds.strKey));
                                }
                                else
                                {
                                    if (ishadProcContext==false)
                                    {
                                        newObjJs.AppendLine("/*自动定义存储过程对象*/");
                                        ishadProcContext=true;
                                    }
                                    newObjJs.AppendLine("Aspfm.Data." + bp.strKey + "_" + bds.strKey + "=new Object();");
                                }
                            }
                        }
                        if (bp.UpdateList != null)
                        {
                            if (bp.UpdateList.Count > 0)
                            {
                                newObjJs.AppendLine("/*自动定义保存对象*/");
                                foreach (AspfmUpdateSql bds in bp.UpdateList)
                                {
                                    newObjJs.AppendLine("Aspfm.Data." + bp.strKey + "_" + bds.strKey + "=new Object();");
                                }
                            }
                        }
                        if (bp.sqlList != null)
                        {
                            bool ishadSQLContext = false;
                            foreach (AspfmDataSql bds in bp.sqlList)
                            {
                                if (bds.IsSimpleSql)
                                {
                                    if (ishadSQLContext == false)
                                    {
                                        newObjJs.AppendLine("/*自动定义简易查询对象*/");
                                        ishadSQLContext = true;
                                    }
                                    newObjJs.AppendLine("Aspfm.Data." + bp.strKey + "_" + bds.strKey + "=new Object();");
                                }
                                else
                                {
                                    string strhtml = "";
                                    string strhtmlFunc = "";
                                    if (JsBandHtml_Data.ContainsKey(bds.strKey))
                                    {
                                        strhtmlFunc = "/*控件绑定数据源的JS函数初始化*/\r\n";
                                        string[] strs = JsBandHtml_Data[bds.strKey].Split(',');
                                        foreach (string str in strs)
                                        {
                                            strhtmlFunc += "if(init" + str + "){init" + str + "(datalist,'" + bds.strKey + "');}\r\n";
                                        }
                                    }
                                    if (JsBandHtml_col.ContainsKey(bds.strKey))
                                    {
                                        string[] strs = JsBandHtml_col[bds.strKey].Split(',');
                                        foreach (string str in strs)
                                        {
                                            strhtmlFunc += "if(initcol" + str + "){initcol" + str + "(datalist,'" + bds.strKey + "');}\r\n";
                                        }
                                    }
                                    if (bds.Htmlstr.Contains("@Aspfm-bandjsFunc"))
                                    {
                                        bds.Htmlstr = bds.Htmlstr.Replace("@Aspfm-bandjsFunc", strhtmlFunc);
                                    }
                                    else
                                    {
                                        strhtml = strhtmlFunc;
                                    }
                                    string[] cols = bds.columns.Split(',');
                                    foreach (string col in cols)
                                    {
                                        if (!string.IsNullOrEmpty(col.Trim()))
                                        {
                                            string strtemp = GetHtml(bds.strKey, col, "data.");
                                            if (!string.IsNullOrEmpty(strtemp))
                                            {
                                                strhtml += strtemp + "\r\n";
                                            }
                                        }
                                    }
                                    bds.Htmlstr = bds.Htmlstr.Replace("@Aspfm-bandjs", strhtml);
                                    sbhtml.AppendLine("/*sql查询：" + bp.strKey + "_" + bds.strKey + "*/");
                                    sbhtml.AppendLine(bds.Htmlstr.Replace("@参数名称", bp.strKey + "_" + bds.strKey));
                                }
                            }
                        }
                    }
                }
            }
            return sbhtml;
        }

        private string GetHtml(string treename,string key,string tagsig)
        {
            string strhtml = "";
            if (JsBandHtml.ContainsKey(treename + "." + key))
            {
                string[] strs = JsBandHtml[treename + "." + key].Split(',');
                foreach (string str in strs)
                {
                    strhtml += "Aspfm.Data.Form." + str + "=" + tagsig + key + ";";
                }
            }
            return strhtml;
        }

        private List<AspfmEntity> sortlist(List<AspfmEntity> DesignList)
        {
            var sortedList = DesignList.OrderBy(a => a.Locations.Y).ThenBy(a => a.Locations.X);
            DesignList = sortedList.ToList(); //这个时候会排序
            return DesignList;
        }

        public StringBuilder CreateHtml(List<AspfmEntity> DesignList, int x, int y, string RowLevel)
        {
            if (DesignList != null && DesignList.Count > 0)
            {
                x = x - 22;
                y = y - 22;
                List<StringBuilder> ColList = new List<StringBuilder>();
                int currenty = 0;
                StringBuilder bCol = new StringBuilder();
                double tempcolcount = 0;

                DesignList = sortlist(DesignList);
                foreach (AspfmEntity Aspfm in DesignList)
                {
                    if (Aspfm.Locations.Y > (currenty + 9))
                    {
                        tempcolcount = 0;
                        currenty = Aspfm.Locations.Y;
                        ColList.Add(bCol);
                        bCol = new StringBuilder();
                    }
                    double col = Math.Round((((double)Aspfm.Sizes.Width) / x), 4, MidpointRounding.AwayFromZero);
                    col = Math.Round(col * 100, 2, MidpointRounding.AwayFromZero);
                    if (tempcolcount + col > colcount || (Aspfm.Sizes.Width+Aspfm.Locations.X)>(x-9))
                    {
                        col = colcount - tempcolcount;
                    }
                    tempcolcount += col;
                    bCol.AppendLine("<!-- 组件HTML：" + Aspfm.ID+ " -->");
                    bCol.Append(GetCol(Aspfm, x, y, ColList.Count, col, tempcolcount, RowLevel));
                }
                ColList.Add(bCol);

                StringBuilder sbhtml = new StringBuilder();

                for (int i = 0; i < ColList.Count; i++)
                {
                    string rowhtml = RowHtml;
                    rowhtml = rowhtml.Replace("@Aspfm-正文", ColList[i].ToString());
                    rowhtml = rowhtml.Replace("@Rowid", "aspfmrow" + RowLevel+"-" + i.ToString());
                    sbhtml.AppendLine(rowhtml);
                }
                return sbhtml;
            }
            return new StringBuilder("&nbsp;");//DIV内部为空。返回空格
        }

        private string GetFullDataSource(string _DataSource)
        {
            if (!string.IsNullOrEmpty(_DataSource))
            {
                foreach (AspfmDataSource ds in MyDataSql)
                {
                    if (ds.sqlList != null)
                    {
                        foreach (AspfmDataSql sql in ds.sqlList)
                        {
                            if (sql.strKey == _DataSource)
                            {
                                return ds.strKey + "_" + _DataSource;
                            }
                        }
                    }
                    if (ds.procList != null)
                    {
                        foreach (AspfmProcSql sql in ds.procList)
                        {
                            if (sql.strKey == _DataSource)
                            {
                                return ds.strKey + "_" + _DataSource;
                            }
                        }
                    }
                }
            }
            return "";
        }

        private StringBuilder GetHtml(AspfmEntity Aspfm, string RowLevel)
        {
            StringBuilder bCol = new StringBuilder(Aspfm.Html);
            if (Aspfm.typekey != AspfmType.TabGroup)
            {
                bCol = bCol.Replace("@Aspfm-Id", Aspfm.ID);
                bCol = bCol.Replace("@Aspfm-text", Aspfm.Text);
                bCol = bCol.Replace("@Rowid", "aspfmrow" + RowLevel);
                string isShowTitle = "true";
                if (Aspfm.typekey == AspfmType.Div)
                {
                    isShowTitle = "false";
                }
                bCol = bCol.Replace("@Aspfm-IsTitle", isShowTitle);
                bCol = bCol.Replace("@Aspfm-查询字段", Aspfm.QueryCol);
                bCol = bCol.Replace("@Aspfm-查询结果集", Aspfm.DataSource);
                bCol = bCol.Replace("@查询sql", GetFullDataSource(Aspfm._DataSource));
                if (!string.IsNullOrEmpty(Aspfm.QueryCol))
                {
                    if (Aspfm.HtmlText.js.Replace(" ", "").Contains("functioninitcol@Aspfm-Id(datalist"))
                    {
                        string[] strs1 = Aspfm.QueryCol.Split(new char[]{','},StringSplitOptions.RemoveEmptyEntries);
                        foreach (string str in strs1)
                        {
                            AddJsBand(str.Split('.')[0], Aspfm.ID, true,true);
                        }
                    }
                    AddJsBand(Aspfm.QueryCol,Aspfm.ID);
                }
            }
            
            return bCol;
        }
        public StringBuilder GetCol(AspfmEntity Aspfm, int x, int y, int colindex, double col, double tempcolcount, string RowLevel)
        {
            if (!string.IsNullOrEmpty(Aspfm.DataSource))
            {
                if (Aspfm.HtmlText.js.Replace(" ", "").Contains("functioninit@Aspfm-Id(datalist"))
                {
                    AddJsBand(Aspfm.DataSource, Aspfm.ID, true);
                }
            }
            RowLevel = RowLevel + "-" + colindex.ToString();
            StringBuilder bColhtml = GetHtml(Aspfm,RowLevel);
            
            bColhtml = bColhtml.Replace("@Aspfm-col",col.ToString());
            if (tempcolcount == colcount)
            {
                bColhtml.Replace("col_custom", "col_custom_end");
                bColhtml.Replace("col_custom_end_end", "col_custom_end");
            }
            if (Aspfm.typekey == AspfmType.TabGroup)
            {
                for (int i = 0; i < Aspfm.ChildList.Count; i++)
                {
                    StringBuilder bCol = CreateHtml(Aspfm.ChildList[i].ChildList, Aspfm.Sizes.Width, Aspfm.Sizes.Height, RowLevel);
                    bColhtml = bColhtml.Replace("@Aspfm-text" + (i + 1), Aspfm.ChildList[i].Text);
                    bColhtml = bColhtml.Replace("@Aspfm-Id" + (i + 1), Aspfm.ID + (i + 1));
                    bColhtml = bColhtml.Replace("@Aspfm-正文" + (i + 1), bCol.ToString());
                }
            }
            else
            {
                StringBuilder bCol = CreateHtml(Aspfm.ChildList, Aspfm.Sizes.Width, Aspfm.Sizes.Height, RowLevel);
                bColhtml.Replace("@Aspfm-正文", bCol.ToString());
            }
            bColhtml = RemoveCssAndJs(bColhtml, Aspfm, colindex, RowLevel);
            return bColhtml;
        }

        private StringBuilder RemoveCssAndJs(StringBuilder bColhtml, AspfmEntity Aspfm, int rowindex, string RowLevel)
        {
            string str = bColhtml.ToString();
            //for (; str.Contains("<script>"); )
            //{
            //    int scriptindex = str.IndexOf("<script>");
            //    int scriptend = str.IndexOf("</script>");
            //    //str = str.Substring(scriptindex + "<script>".Length, scriptend - scriptindex - "<script>".Length);
            //    sbHtmlJs.AppendLine("/*组件：" + Aspfm.ID + "*/");
            //    sbHtmlJs.AppendLine(str.Substring(scriptindex + "<script>".Length, scriptend - scriptindex - "<script>".Length).Trim());
            //    bColhtml = bColhtml.Remove(scriptindex, scriptend - scriptindex + "</script>".Length);
            //    str = bColhtml.ToString();
            //}
            //for (; str.Contains("<style>"); )
            //{
            //    int styleindex = str.IndexOf("<style>");
            //    int styleend = str.IndexOf("</style>");
            //    sbHtmlCss.AppendLine("/*组件：" + Aspfm.ID + "*/");
            //    //str = str.Substring(styleindex + "<style>".Length, styleend - styleindex - "<style>".Length);
            //    sbHtmlCss.AppendLine(str.Substring(styleindex + "<style>".Length, styleend - styleindex - "<style>".Length).Trim());
            //    bColhtml = bColhtml.Remove(styleindex, styleend - styleindex + "</style>".Length);
            //    str = bColhtml.ToString();
            //}

            for (; str.Contains("<script"); )
            {
                int styleindex = str.IndexOf("<script");
                int styleend = str.IndexOf("</script>");
                //sbHtmlScript.AppendLine("/*组件模板：" + Aspfm.ID + "*/");
                //str = str.Substring(styleindex + "<style>".Length, styleend - styleindex - "<style>".Length);
                sbHtmlScript.AppendLine(str.Substring(styleindex, styleend - styleindex).Trim() + "</script>");
                bColhtml = bColhtml.Remove(styleindex, styleend - styleindex + "</script>".Length);
                str = bColhtml.ToString();
            }
            if (Aspfm.HtmlText != null)
            {
                if (!string.IsNullOrEmpty(Aspfm.HtmlText.js))
                {
                    sbHtmlJs.AppendLine("/*组件：" + Aspfm.ID + "   " + Aspfm._dbremark+ "*/");
                    string js = Aspfm.HtmlText.js.Replace("@Aspfm-text", Aspfm.Text);
                    js = js.Replace("@Aspfm-Id", Aspfm.ID);
                    js = js.Replace("@查询sql", GetFullDataSource(Aspfm.DataSource));
                    js = js.Replace("@Rowid", "aspfmrow" + RowLevel+"-" + rowindex.ToString());
                    sbHtmlJs.AppendLine(js);
                }
            }
            return bColhtml.Replace("\r\n","");
        }
    }
}
